﻿namespace WebMarkupMin.Example.Mvc.Controllers
{
	using System.Web.Mvc;

	using AutoMapper;

	using Core;
	using Core.Minifiers;
	using Core.Settings;
	using ViewModels;
	using ViewModels.Settings;
	using WebMarkupMin.Mvc.ActionFilters;

    public class HtmlMinifierController : Controller
    {
		[HttpGet]
		[CompressContent]
		[MinifyHtml]
		[OutputCache(CacheProfile = "CacheCompressedContent5Minutes")]
        public ActionResult Index()
		{
			var model = InitModel();

			return View(model);
		}

		[HttpPost]
		[ValidateInput(false)]
		public ActionResult Index(FormCollection collection)
		{
			var model = InitModel();

			TryUpdateModel(model, new[] { "SourceCode", "Settings" }, collection);

			if (ModelState.IsValid)
			{
				string cssMinifierName = model.Settings.CssMinifierName;
				string jsMinifierName = model.Settings.JsMinifierName;

				var settings = Mapper.Map<HtmlMinificationSettings>(model.Settings);
				CodeContext codeContext = WebMarkupMinContext.Current.Code;
				ICssMinifier cssMinifier = codeContext.CreateCssMinifierInstance(cssMinifierName, false);
				IJsMinifier jsMinifier = codeContext.CreateJsMinifierInstance(jsMinifierName, false);

				var htmlMinifier = new HtmlMinifier(settings, cssMinifier, jsMinifier);
				var result = htmlMinifier.Minify(model.SourceCode, true);

				model.Result = Mapper.Map<MarkupMinificationResultViewModel>(result);

				ModelState.Clear();
			}

			return View(model);
		}

		[NonAction]
		private HtmlMinificationViewModel InitModel()
		{
			var settings = Mapper.Map<HtmlMinificationSettingsViewModel>(new HtmlMinificationSettings());
			var model = new HtmlMinificationViewModel
			{
				SourceCode = string.Empty,
				Settings = settings,
				Result = null
			};

			return model;
		}
	}
}